import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { useRouter } from 'next/router';
import { Form, Input, Select, Button, DatePicker, message, Row, Col, Space } from 'antd';
import { storyOptions, reviewer, reviewStatus } from '@/utils/data';
import dayjs from 'dayjs';
import PageTitle from '@/components/pageTitle';
import { updateStoryApi, addStoryApi, story_list, getLockStatusApi, closeScheduleApi, submitScheduleApi, getOnLockApi } from '@/request/story';
import Icon from '@/components/layout/Icon';
import { useHeight } from '@/utils/hooks/pagination';
import { v4 } from 'uuid';
import Trapezium from '@/components/trapezium';
import Diamond from '@/components/diamond';
import RelationTable from '../components/relationTable';
import styles from './index.module.css';
import SchedulePlan from '../components/schedulePlan';

const { RangePicker } = DatePicker;
const { TextArea } = Input;

const typesCom = {
  input: Input,
  rangeTime: RangePicker,
  datePicker: DatePicker,
};

interface Query {
  id?: string;
  [props: string]: any;
}
const columns: any = (handlerOperation, checkLoading, developEnv) => [
  {
    title: '项目名称',
    dataIndex: 'project_name',
    width: '230px',
    fixed: 'left',
    render: (text: string, record: any) => (
      <div className={styles.link_div} onClick={() => window.open(record.http_url_to_repo)}>
        {text}
      </div>
    ),
  },
  {
    title: '项目分支',
    dataIndex: 'branch',
    width: '200px',
    render: (text: string, record: { http_url_to_repo: string; branch: string }) => (
      <div className={styles.link_div} onClick={() => window.open(`${(record.http_url_to_repo || '').replace('.git', '')}/-/tree/${record.branch}`)}>
        {text}
      </div>
    ),
  },
  {
    title: '开发环境',
    dataIndex: 'env',
    width: '230px',
    render(text, record, index) {
      let arr: any = [];
      if (Array.isArray(record.envList)) {
        arr = record.envList.map((item) => ({ label: item, value: item }));
      } else if (Array.isArray(developEnv)) {
        arr = developEnv;
      }
      if (arr && arr.length) {
        return (
          <Select
            onChange={(e) => {
              handlerOperation('env', record, index, e);
            }}
            style={{ width: '180px' }}
            placeholder="请选择开发环境"
            value={text}
            options={arr}
            mode="multiple"
          />
        );
      }
      if (text) {
        return text.toString();
      }
      return '-';
    },
  },
  {
    title: '开发人',
    dataIndex: 'developer',
    width: '120px',
    render(text) {
      if (!text || text.length <= 0) return <span>-</span>;
      if (Array.isArray(text)) {
        return <span>{text.join('，')}</span>;
      }
      return <span>{text}</span>;
    },
  },
  {
    title: 'review状态',
    dataIndex: 'review_status',
    width: '150px',
    render(text, record, index) {
      return (
        <Select
          style={{ width: '120px' }}
          options={reviewStatus}
          placeholder="review状态"
          value={text}
          onChange={(e) => {
            handlerOperation('status', record, index, e);
          }}
        ></Select>
      );
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '280px',
    fixed: 'right',
    className: 'table-operation',
    render(text, record, index) {
      return (
        <Space wrap>
          <Button
            className="btn-link"
            type="link"
            onClick={() => {
              handlerOperation('diff', record);
            }}
          >
            diff分支地址
          </Button>
          <Button
            className="btn-link"
            type="link"
            onClick={() => {
              handlerOperation('record', record);
            }}
          >
            提交记录
          </Button>
          <Button
            className="btn-link"
            disabled={checkLoading}
            type="link"
            onClick={() => {
              handlerOperation('check', record);
            }}
          >
            代码质量检查
          </Button>
          <Button
            className="btn-link"
            type="link"
            onClick={() => {
              handlerOperation('delete', record, index);
            }}
          >
            取消关联
          </Button>
        </Space>
      );
    },
  },
];

const editTab = [
  { title: '排期计划', key: 'plan' },
  { title: '关联项目', key: 'relation' },
];

const StoryEdit = (props) => {
  const ref = useRef<any>(null);
  const router: Query = useRouter();
  const { id } = router.query;
  const [detail, setDetail] = useState<any>({});
  const relationTable = useRef<any>(null);
  const [form] = Form.useForm();
  const { height } = useHeight(130);
  const [basicOpen, setBasicOpen] = useState(true); // 基本信息开关
  const [activeKey, setActiveKey] = useState('plan');
  const [lockInfo, setLockInfo] = useState<any>({ isLock: true });
  const [loading, setLoading] = useState(false);

  // 获取锁状态
  const getLockInfo = async (ids: string) => {
    try {
      const res: any = await getOnLockApi({ storyId: ids });
      if (!res) {
        setLockInfo({ isLock: false });
      } else {
        setLockInfo({ isLock: true });
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };

  // 查询数据
  const queryInfo = async (ids: string) => {
    if (!ids) return;
    try {
      const result: any = await story_list({ id: ids });
      if (result.data) {
        const res = result.data[0];
        setDetail(res);
        if (activeKey === 'plan') {
          getLockInfo(res._id);
        }
        if (res.online_time) {
          res.online_time = dayjs(res.online_time);
        }
        form.setFieldsValue(res);
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };

  useEffect(() => {
    if (id && id !== '0') {
      queryInfo(id as string);
    }
  }, [id]);

  const onFinish = async () => {
    const data = form.getFieldsValue();
    const temp = {
      ...detail,
      ...data,
      online_time: dayjs(data.online_time).format('YYYY-MM-DD'),
      source: detail.source || 'local',
    };
    if (id && id !== '0') {
      temp.id = id;
    } else {
      temp.id = v4();
      temp.created = dayjs().format('YYYY-MM-DD HH:mm:ss');
      temp.source = 'local';
    }
    Object.keys(temp).forEach((item) => {
      if (temp[item] === null) {
        delete temp[item];
      }
    });
    try {
      const res: any = await (id === '0' ? addStoryApi(temp) : updateStoryApi(temp));
      if (res) {
        message.success('保存成功');
        // router.push('/storyManage');
      } else {
        message.error('保存失败');
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };
  const statusBox = () => {
    const res = detail.relation_projects || [];
    if (res.length) {
      for (let i = 0; i < res.length; i += 1) {
        if (res[i].review_status === 1) {
          return '待修改';
          // return <span>待修改</span>;
        }
        if (res[i].review_status === 0) {
          return '未查验';
          // return <span>未查验</span>;
        }
      }
      return '已查验';
      // return <span>已查验</span>;
    }
    return '暂无';
    // return <span>暂无</span>;
  };

  // 开锁
  const handleCheckLock = async (ids) => {
    if (!ids) return;
    setLoading(true);
    try {
      const res: any = await getLockStatusApi({ storyId: ids });
      if (res?.isLock) {
        setLockInfo({ isLock: true });
        message.warning(`该需求正在被${res.personName as string}修改,请稍后再操作`);
      } else {
        setLockInfo({ isLock: false });
      }
      setLoading(false);
    } catch (err) {
      setLoading(false);
      console.log(err);
    }
  };

  // 内容改变调接口
  const dataChange = async (params, ids) => {
    if (!ids) return;
    try {
      const res = await submitScheduleApi({ ...params, storyId: ids });
    } catch (err: any) {
      message.warning(err.message);
    }
  };

  // 关锁
  const handleUnlock = async (ids) => {
    if (!ids) return;
    setLoading(true);
    try {
      const res: any = await closeScheduleApi({ storyId: ids });
      const data = ref.current.getData();
      dataChange(data, ids);
      setLockInfo({ isLock: true });
      setLoading(false);
    } catch (err) {
      setLoading(false);
      console.log(err);
    }
  };

  // 切换tab
  const handleTabChange = (key: string) => {
    setActiveKey(key);
    if (key === 'plan') {
      getLockInfo(detail._id);
    }
  };

  // 按钮内容
  const btnContent = useMemo(() => {
    let dom = <div></div>;
    switch (activeKey) {
      case 'relation':
        dom = (
          <Button
            className="flex"
            icon={<Icon src="/images/add-blue.png" width={16} height={16} style={{ marginRight: '4px' }} />}
            onClick={() => {
              relationTable.current.handleOpen();
            }}
          >
            添加项目
          </Button>
        );
        break;
      case 'plan':
        dom = (
          <Button
            className="flex"
            loading={loading}
            onClick={() => {
              if (lockInfo?.isLock) {
                handleCheckLock(detail._id);
              } else {
                handleUnlock(detail._id);
              }
            }}
          >
            {lockInfo?.isLock ? '开锁' : '关锁'}
          </Button>
        );
        break;
      default:
        break;
    }
    return dom;
  }, [activeKey, lockInfo?.isLock, loading, detail._id]);

  return (
    <div className="story-edit">
      <PageTitle
        title={detail.name || '自创建需求'}
        extra={
          <div>
            <Button
              style={{ marginRight: '10px' }}
              onClick={() => {
                router.back();
              }}
            >
              取消
            </Button>
            <Button
              type="primary"
              onClick={() => {
                onFinish();
              }}
            >
              保存
            </Button>
          </div>
        }
      />
      <div style={{ height, overflowY: 'scroll', paddingRight: 10 }}>
        <div className={styles.cate}>
          <div className={styles.line}></div>
          <div className={styles.cateName}>基本信息</div>
        </div>
        <div className={`${styles.basicInfo} ${basicOpen ? styles.open : ''}`}>
          <Form
            // labelCol={{ flex: '100px' }}
            // wrapperCol={{ flex: 'auto' }}
            layout="inline"
            form={form}
            onFinish={() => {
              onFinish();
            }}
          >
            <Row wrap style={{ width: '100%', paddingLeft: '10px' }}>
              <Col span={8}>
                <Form.Item label="需求名称" name="name" className={styles['form-item']}>
                  <Input placeholder="请输入" style={{ width: '100%' }} disabled={detail.source === 'tapd'} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="需求状态" name="status" className={styles['form-item']}>
                  <Select options={storyOptions} style={{ width: '100%' }} placeholder="请选择" disabled={detail.source === 'tapd'}></Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="代码查验人" name="reviewer" className={styles['form-item']}>
                  <Select options={reviewer} placeholder="请选择" mode="multiple" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="查验状态" className={styles['form-item']}>
                  <Input placeholder="请输入" style={{ width: '100%' }} disabled={detail.source === 'tapd'} value={statusBox()} />
                  {/* {statusBox} */}
                </Form.Item>
              </Col>
              {/* <Col span={8}>
                <Form.Item label="开发开始时间" name="develop_start_time" className={styles['form-item']}>
                  <DatePicker placeholder="请选择时间" style={{ width: '100%' }} disabled={detail.source === 'tapd'} suffixIcon={<Icon src="/images/date.png" width={16} height={16} />} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="联调时间" name="develop_uniting" className={styles['form-item']}>
                  <DatePicker placeholder="请选择时间" style={{ width: '100%' }} disabled={detail.source === 'tapd'} suffixIcon={<Icon src="/images/date.png" width={16} height={16} />} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="验收时间" name="check_time" className={styles['form-item']}>
                  <DatePicker placeholder="请选择时间" style={{ width: '100%' }} disabled={detail.source === 'tapd'} suffixIcon={<Icon src="/images/date.png" width={16} height={16} />} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="可发灰度时间" name="gray_time" className={styles['form-item']}>
                  <DatePicker placeholder="请选择时间" style={{ width: '100%' }} disabled={detail.source === 'tapd'} suffixIcon={<Icon src="/images/date.png" width={16} height={16} />} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="提测时间" name="submit_test_time" className={styles['form-item']}>
                  <DatePicker placeholder="请选择时间" style={{ width: '100%' }} disabled={detail.source === 'tapd'} suffixIcon={<Icon src="/images/date.png" width={16} height={16} />} />
                </Form.Item>
              </Col> */}
              <Col span={8}>
                <Form.Item label="上线时间" name="online_time" className={styles['form-item']}>
                  <DatePicker format="YYYY-MM-DD" placeholder="请选择时间" style={{ width: '100%' }} suffixIcon={<Icon src="/images/date.png" width={16} height={16} />} />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        {/* <div className={`${styles.basicFlag} ${!basicOpen ? styles.bottom : ''}`}>
          <Icon src="/images/top.svg" onClick={() => setBasicOpen(!basicOpen)} />
        </div> */}
        <div className={styles.content}>
          <div className={styles.tab}>
            {editTab.map((it, i) => {
              return i === 0 ? (
                <Trapezium key={i} text={it.title} style={{ marginRight: '10px' }} actived={activeKey === it.key} onClick={() => handleTabChange(it.key)} />
              ) : (
                <Diamond key={i} text={it.title} actived={activeKey === it.key} onClick={() => handleTabChange(it.key)} />
              );
            })}
          </div>
          <div className={styles.tabControls}>{btnContent}</div>
        </div>
        {id && id !== '0' && activeKey === 'relation' && (
          <>
            {/* <Row justify="space-between" style={{ marginBottom: '20px' }}>
              <div className={styles.cate} style={{ marginBottom: '0' }}>
                <div className={styles.line}></div>
                <div className={styles.cateName}>关联项目</div>
              </div>
              <Button
                className="flex"
                icon={<Icon src="/images/add-blue.png" width={16} height={16} style={{ marginRight: '4px' }} />}
                onClick={() => {
                  relationTable.current.handleOpen();
                }}
              >
                添加项目
              </Button>
            </Row> */}
            <RelationTable myRecord={detail} columns={columns} ref={relationTable} style={{ paddingLeft: '10px', marginBottom: '20px' }} scrollY={400} />
          </>
        )}
        {/* <Row justify="space-between" style={{ marginBottom: '20px' }}>
          <div className={styles.cate} style={{ marginBottom: '0' }}>
            <div className={styles.line}></div>
            <div className={styles.cateName}>排期计划</div>
          </div>
          <Button
            className="flex"
            onClick={() => {
              handleCopyPlan();
            }}
          >
            一键复制
          </Button>
        </Row> */}
        {activeKey === 'plan' && (
          <div className={styles.schedule}>
            <SchedulePlan ref={ref} detailData={detail} lockInfo={lockInfo} setLockInfo={setLockInfo} />
            {/* <Form initialValues={planInitFormValue} form={planForm} labelCol={{ flex: '100px' }} wrapperCol={{ flex: 'auto' }} layout="inline">
              <Row>
                {planFormItems.map((item) => {
                  const FormItemCom = typesCom[item.type];
                  return (
                    <Col span={8} key={item.name}>
                      <Form.Item name={item.name} label={item.label} className={styles['form-item']}>
                        <FormItemCom style={{ width: '100%' }} />
                      </Form.Item>
                    </Col>
                  );
                })}
              </Row>
              <Col span={24} className={styles['form-item']}>
                <div>预计工时统计 总计：{totalCost}h</div>
              </Col>
              <PlanItemBlock formListName="requirement" decs="需求评审" form={planForm} costTotal={requirementCost} handleCost={(total) => setRequirementCost(total)} />
              <PlanItemBlock formListName="front" decs="前端开发" form={planForm} costTotal={frontCost} handleCost={(total) => setFrontCost(total)} />
              <PlanItemBlock formListName="backend" decs="后端开发" form={planForm} costTotal={backendCost} handleCost={(total) => setBackendCost(total)} />
              <PlanItemBlock formListName="app" decs="App开发" form={planForm} costTotal={appCost} handleCost={(total) => setAppCost(total)} />
              <PlanItemBlock formListName="BD" decs="大数据开发" form={planForm} costTotal={BDCost} handleCost={(total) => setBDCost(total)} />
              <PlanItemBlock formListName="case" decs="用例撰写时间" form={planForm} costTotal={caseCost} handleCost={(total) => setCaseCost(total)} />
              <PlanItemBlock formListName="test" decs="测试时间" form={planForm} costTotal={testCost} handleCost={(total) => setTestCost(total)} />
              <PlanItemBlock formListName="cross" decs="交叉测试" form={planForm} costTotal={crossCost} handleCost={(total) => setCrossCost(total)} />
              <PlanItemBlock formListName="online" decs="灰度+线上验证" form={planForm} costTotal={onlineCost} handleCost={(total) => setOnlineCost(total)} />
              <Col span={24} className={styles['form-item']}>
                <Form.Item label="提测环境" name="testEnv">
                  <Select options={env} style={{ width: '300px' }}></Select>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item label="测试范围" name="testRange">
                  <TextArea maxLength={200} style={{ width: '300px' }} />
                </Form.Item>
              </Col>
            </Form> */}
          </div>
        )}
      </div>
    </div>
  );
};

// export function getStaticPaths() {
//   // ...
//   return { paths: [{ params: { id: '2' } }], fallback: false };
// }

// export function getStaticProps({ params }) {
//   const res = { name: 'zs', id: params.id };
//   return {
//     props: { res },
//   };
// }

export default StoryEdit;
